import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import { getToken } from '@/utils/cookies';

const Message = window['$message'];

const fileRequest = axios.create({
	baseURL: import.meta.env.VITE_BASE_API,
});

// request interceptor
fileRequest.interceptors.request.use(
	config => {
		// do something before request is sent
		if (getToken()) {
			config.headers!['token'] = getToken();
		}
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);
fileRequest.interceptors.response.use(
	response => {
		// const res = response.data
		// return res
		return response;
	},
	error => {
		let data = error.response.data;
		if (error.request.responseType === 'blob') {
			const reader = new FileReader();
			reader.readAsText(data, 'utf-8');
			reader.onload = function () {
				data = JSON.parse(String(reader.result));
				Message.error(data.message);
				return Promise.reject(data);
			};
		}
	}
);

/** 文件下载回调 */
export interface CallbackType {
	/** 下载成功回调 */
	successCallback?: Function;
	/** 下载失败回调 */
	faildCallback?: Function;
	/** 文件名 */
	fileName?: string;
}

/** 文件下载 请求拦截器
 * @author wx
 * @param config 请求配置
 * @param callback 回调函数
 * @param callback.successCallback 成功回调函数
 * @param callback.faildCallback 失败回调函数
 * @param callback.fileName 文件名,不传则使用接口响应中的文件名
 */
async function fileDownload<T>(config: AxiosRequestConfig<T>, callback: CallbackType = {}) {
	// const fileDownload = async(config:AxiosRequestConfig, callback:CallbackType = {}) => {
	const { successCallback, faildCallback, fileName } = callback;
	try {
		const res = await fileRequest({ ...config, responseType: 'blob' });

		let xhrname = fileName;
		if (!fileName) {
			// const cd = decodeURI(res.headers['content-disposition'], 'utf-8');
			// const cd = decodeURI(res.headers['content-disposition']);
			const cd = decodeURIComponent(res.headers['content-disposition']);

			xhrname = cd.split('=')[1].replace('"', '').replace('"', '');
			console.log(cd);
			console.log(xhrname);
		}
		const blob = res.data;
		// 如果支持blob类型的下载，Firefox,Chrome等浏览器支持download，IE10以上支持blob，但是依然不支持的download
		// @ts-ignore
		if (window.navigator.msSaveOrOpenBlob) {
			// @ts-ignore
			navigator.msSaveBlob(blob, xhrname);
			successCallback && successCallback();
		} else {
			const link = document.createElement('a');
			const body = document.querySelector('body')!;
			link.href = window.URL.createObjectURL(blob);
			link.download = xhrname!;
			// fix Firefox
			link.style.display = 'none';
			body.appendChild(link);
			link.click();
			body.removeChild(link);
			window.URL.revokeObjectURL(link.href);
			successCallback && successCallback();
		}
	} catch (error) {
		faildCallback && faildCallback(error);
	}
}

export default fileDownload;
